#!/bin/bash
set -e

# Configuration
APP_NAME="deepseek-chat"
VERSION="1.0.0"
DIST_DIR="dist"
OUTPUT_NAME="$APP_NAME-$VERSION"

# Clean dist directory
rm -rf "$DIST_DIR"
mkdir -p "$DIST_DIR"

# Build the binary
echo "Building binary for Linux/AMD64..."
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o "$DIST_DIR/$APP_NAME" cmd/server/main.go

# Prepare staging directory
STAGING_DIR="$DIST_DIR/$OUTPUT_NAME"
mkdir -p "$STAGING_DIR"

# Copy binary and static files
cp "$DIST_DIR/$APP_NAME" "$STAGING_DIR/"
cp -r static "$STAGING_DIR/"
cp -r configs "$STAGING_DIR/"
cp server.sh "$STAGING_DIR/"
cp README.md "$STAGING_DIR/"

# Create tar.gz
echo "Packaging to $DIST_DIR/$OUTPUT_NAME.tar.gz..."
cd "$DIST_DIR"
tar -czf "$OUTPUT_NAME.tar.gz" "$OUTPUT_NAME"

# Cleanup staging
rm -rf "$OUTPUT_NAME"
rm "$APP_NAME" # Remove the loose binary in dist

echo "Build complete! Package is at $DIST_DIR/$OUTPUT_NAME.tar.gz"
